package com.scau.ums.service.imp.password;

import com.scau.ums.mapper.MaintainerMapper;
import com.scau.ums.mapper.StudentMapper;
import com.scau.ums.mapper.TeacherMapper;
import com.scau.ums.model.*;
import com.scau.ums.service.imp.info.DefaultSendInfoImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * author: 莫伟杰
 * date： 2019/7/26 14:54
 */

//使用时必须设置userType属性，否则部分功能无法使用
@Service
public class CommonPasswordImp extends PasswordImp {
    private int userType;
    private StudentMapper studentMapper;
    private TeacherMapper teacherMapper;
    private MaintainerMapper maintainerMapper;
    private DefaultSendInfoImp sendInfoImp;

    @Autowired
    public CommonPasswordImp(StudentMapper studentMapper, TeacherMapper teacherMapper, MaintainerMapper maintainerMapper) {
        this.studentMapper = studentMapper;
        this.teacherMapper = teacherMapper;
        this.maintainerMapper = maintainerMapper;
    }

    @Autowired
    public void setSendInfoImp(DefaultSendInfoImp sendInfoImp) {
        this.sendInfoImp = sendInfoImp;
    }

    public int getUserType() {
        return userType;
    }

    public void setUserType(int userType) {
        this.userType = userType;
    }

    //普通用户重置密码为USER_ID
    @Override
    public boolean resetPassword(String userID) {
        User user = getUserByType(userID);
        if(user==null) return false;
        user.setPassword(encode(userID));
        return false;
    }

    @Override
    public boolean changePassword(String userID, String oldPwd, String newPwd) {
        User user = getUserByType(userID);
        if(user==null) return false;
        if(!matches(oldPwd,user.getPassword())) return false;
        user.setPassword(encode(newPwd));
        if(!updateUserByType(user)) return false;
        Info info = sendInfoImp.createInfo("修改密码成功","system",user.getId(),User.userTypeToChinese(userType),
                "您的密码已成功修改！请牢记您的新密码。如果不是您本人操作，请联系管理员重置密码。");
        sendInfoImp.sendInfo(info);
        return true;
    }

    private User getUserByType(String userID)
    {
        switch (userType)
        {
            case User.STUDENT:return studentMapper.selectByPrimaryKey(userID);
            case User.TEACHER:return teacherMapper.selectByPrimaryKey(userID);
            case User.MAINTAINER:return maintainerMapper.selectByPrimaryKey(userID);
            default:return null;
        }
    }

    private boolean updateUserByType(User user)
    {
        switch (userType)
        {
            case User.STUDENT:return studentMapper.updateByPrimaryKey((Student)user)==1;
            case User.TEACHER:return teacherMapper.updateByPrimaryKey((Teacher)user)==1;
            case User.MAINTAINER:return maintainerMapper.updateByPrimaryKey((Maintainer)user)==1;
            default:return false;
        }
    }
}
